package com.jvxb.manage.livable.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Condition;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jvxb.common.utils.CommonUtil;
import com.jvxb.common.utils.ObjectExcelRead;
import com.jvxb.common.web.RespMsg;
import com.jvxb.manage.livable.entity.SysUser;
import com.jvxb.manage.livable.service.SysUserService;
import com.jvxb.modules.configuration.security.SecurityUtil;
import com.jvxb.modules.configuration.security.UserDetail;
import com.jvxb.modules.utils.FileStoreUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author jvxb
 * @since 2020-06-07
 */
@RestController
@RequestMapping("/admin/v1/sysUser")
@Api(tags = "用户相关接口")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    @PostMapping("add")
    public RespMsg<SysUser> add(@RequestBody SysUser user) {
        user.setCreateTime(new Date());
        userService.save(user);
        return RespMsg.ok(user);
    }

    @PostMapping("delete")
    public RespMsg<Void> delete(@RequestBody SysUser user) {
        userService.removeById(user.getId());
        return RespMsg.ok();
    }

    @GetMapping("getUserDetail")
    @ApiOperation("获取用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = false, dataType = "Integer")
    })
    public RespMsg<UserDetail> getUserDetail() {
        UserDetail user = SecurityUtil.currentUser();
        return RespMsg.ok(user);
    }

    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = false, dataType = "String")
    })
    public RespMsg<List<SysUser>> list(String name) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like(StrUtil.isNotEmpty(name), SysUser.USER_NAME, name);
        List<SysUser> list = userService.list(wrapper);
        return RespMsg.ok(list);
    }

    @GetMapping("listPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "size", value = "每页条数，默认10条", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "current", value = "第几页,默认第一页", dataType = "Integer", required = false)
    })
    public RespMsg<IPage<SysUser>> listPage(String name,
                                            @RequestParam(defaultValue = "10") Integer size,
                                            @RequestParam(defaultValue = "1") Integer current) {
        IPage<SysUser> userIPage = new Page<>(current, size);
        QueryWrapper userWrapper = Condition.<SysUser>create();
        userWrapper.eq(SysUser.VALID, 1);
        if (StrUtil.isNotEmpty(name)) {
            userWrapper.last(String.format("and (user_name like '%s%%' or user_code like '%s%%')", name, name));
        }
        userService.page(userIPage, userWrapper);
        Optional.ofNullable(userIPage.getRecords()).ifPresent(e -> e.stream().forEach(u -> u.setPassword(u.getPassword().charAt(0) + "*****")));
        return RespMsg.ok(userIPage);
    }

    @GetMapping("one")
    public RespMsg<SysUser> one(@RequestParam Integer id) {
        SysUser user = userService.getById(id);
        return RespMsg.ok(user);
    }

    @PostMapping("update")
    public RespMsg<SysUser> update(@RequestBody SysUser user) {
        userService.saveOrUpdate(user);
        return RespMsg.ok(user);
    }

    @GetMapping("exportTemplate")
    public void exportTemplate(HttpServletResponse response) {
        try {
            //目标模板文件的位置
            String filePath = "links" + File.separator + "excel" + File.separator + "_template" + File.separator + "userTemplate.xls";
            //下载后显示的名字
            String downLownName = "userTemplate.xls";
            //开始下载
            FileStoreUtil.fileDownload(response, filePath, downLownName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("importUser")
    public RespMsg importUser(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return RespMsg.error("文件为空，请上传文件");
        }
        try {
            //上传excel，并返回excel最终路径
            String excelPath = FileStoreUtil.uploadExcel(file);
            //根据excel路径读取excel: 读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
            List<Map> listUserMap = (List) ObjectExcelRead.readExcel(excelPath, 2, 0, 0);
            System.out.println(listUserMap);
            //根据listUserMap插入数据库，略
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespMsg.ok();
    }

}